<!doctype html>
<html lang='zh-CN'>
  <head>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width,initial-scale=1'>
    <title>upms</title>
  </head>
  <body style="text-align: center">
    <button onclick="OpenWindow('http://gateway-server:9527/oauth2/authorization/gateway-client-oidc')">Login</button>
    <button onclick='TokenInfo()'>TokenInfo</button>
    <button onclick='Logout()'>Logout</button>
    <button onclick="OpenWindow('http://auth-server:9000/logout')">Logout</button>
  </body>
  <script>
    function receiveMessage(messageEvent) {
      console.info(messageEvent);
      console.info('origin', messageEvent.origin);
      console.info('data', JSON.parse(messageEvent.data));
      localStorage.setItem('token', messageEvent.data);
      window.removeEventListener("message", this.receiveMessage);
    }

    function OpenWindow(url) {
      const target = 'window';
      const iWidth = 450; // 弹出窗口的宽度;
      const iHeight = 400 // 弹出窗口的高度;
      const iTop = (window.screen.height - 30 - iHeight) / 2; // 获得窗口的垂直位置;
      const iLeft = (window.screen.width - 10 - iWidth) / 2; // 获得窗口的水平位置;
      const features = 'height=' + iHeight + ',width=' + iWidth + ',top=' + iTop + ',left=' + iLeft;
      // 弹出窗口
      const loginWindow = window.open(url, target, features);
      // 通过监听，父页面可以拿到子页面传递的 token，父(前端页面)，子(小窗)
      window.addEventListener('message', receiveMessage);
      // loginWindow.close();
    }

    // https://wangdoc.com/webapi/fetch

    async function TokenInfo() {
      let head = '', token = '';
      try {
        let data = JSON.parse(localStorage.getItem('token'));
        head = data.key;
        token = data.value;
        console.info(head.concat(' : ').concat(token));
      } catch (error) {
        console.error('Token Error', error);
        return;
      }

      try {
        let headers = new Headers();
        headers.append(head, token);
        let response = await fetch('http://127.0.0.1:9527/upms', {headers, redirect: 'error'});
        console.info(response);
        let json = await response.json();
        console.info(json);
      } catch (error) {
        console.error('Request Failed', error);
      }
    }

    async function Logout() {
      let head = '', token = '';
      try {
        let data = JSON.parse(localStorage.getItem('token'));
        head = data.key;
        token = data.value;
        console.info(head.concat(' : ').concat(token));
      } catch (error) {
        console.error('Token Error', error);
        return;
      }

      try {
        let headers = new Headers();
        headers.append(head, token);
        let response = await fetch('http://127.0.0.1:9527/logout', {method: 'POST', headers, redirect: 'error'});
        console.info(response);
      } catch (error) {
        console.error('Request Failed', error);
      }
    }
  </script>
</html>